<?php
/**
 * Description of ClienteBonusDAO
 *
 * @author Magno
 */
class ClienteBonusDAO {

    private $conexao;
    private $bonusDAO;
    private $clienteDAO;
    

    public function __construct() {
        $this->conexao = Conexao::getConexao();
        $this->bonusDAO = new BonusDAO();
        $this->clienteDAO = new ClienteDAO();        
    }

    public function salvar($clienteBonus) {

        try {

            if ($this->existe($clienteBonus->getBonus()->getBonusID(), $clienteBonus->getCliente()->getUsuarioID())) {

                $statment = $this->conexao->prepare("UPDATE clienteBonus SET
                        valor = :valor,
                        inicio = :inicio,
                        fim = :fim
                        WHERE bonusID = :bonusID AND
                        usuarioID = :usuarioID");
            } else {

                $statment = $this->conexao->prepare("INSERT INTO clienteBonus(bonusID,usuarioID,valor,inicio,fim)
                    VALUES (:bonusID,:usuarioID,:valor,:inicio,:fim);");
            }

            if ($statment->execute($clienteBonus->toBD())) {

                if ($clienteBonus->getClienteBonusID() == null || $clienteBonus->getClienteBonusID() <= 0)
                    $clienteBonus->setClienteBonusID($this->conexao->lastInsertId());
                return $clienteBonus;
            }else {
                $erros = $statment->errorInfo();
                throw new Exception("Erro ClienteBonusDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ClienteBonusDAO:" . $err->getMessage());
        }
    }

    public function excluir($bonusID, $usuarioID) {

        try {

            $statment = $this->conexao->prepare("DELETE FROM clienteBonus WHERE bonusID = :bonusID AND usuarioID = :usuarioID");
            $statment->bindParam(':bonusID', $bonusID);
            $statment->bindParam(':usuarioID', $usuarioID);

            if (!$statment->execute()) {
                $erros = $statment->errorInfo();
                throw new Exception("Erro ClienteBonusDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ClienteBonusDAO:" . $err->getMessage());
        }
    }

    public function listar($pagina = 0, $bonusID = -1, $usuarioID = -1, $inicio = "", $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina);
            $where = $this->getWhere($bonusID, $usuarioID, $inicio);
            $clienteBonuss = array();
            $statment = $this->conexao->query("SELECT * FROM clienteBonus u $where $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $clienteBonus = new ClienteBonusBean(null, null, $row['valor'], $row['inicio'], $row['fim']);

                if($carregarDependencias){
                    $clienteBonus->setBonus($this->bonusDAO->buscarPorID($row['bonusID']));
                    $clienteBonus->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));                   
                }

                $clienteBonuss[] =  $clienteBonus;
            }

            return $clienteBonuss;
        } catch (PDOException $err) {
            throw new Exception("Erro ClienteBonusDAO:" . $err->getMessage());
        }
    }

    public function listarPorOrdem($pagina = 0, $tamanho = 0, $ordem = "bonusID", $direcao = "ASC", $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina,$tamanho);
            $clienteBonuss = array();
            $statment = $this->conexao->query("SELECT * FROM clienteBonus u ORDER BY u.$ordem $direcao $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $clienteBonus = new ClienteBonusBean(null, null, $row['valor'], $row['inicio'], $row['fim']);

                if($carregarDependencias){
                    $clienteBonus->setBonus($this->bonusDAO->buscarPorID($row['bonusID']));
                    $clienteBonus->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }

                $clienteBonuss[] = $clienteBonus;
            }

            return $clienteBonuss;
        } catch (PDOException $err) {
            throw new Exception("Erro ClienteBonusDAO:" . $err->getMessage());
        }
    }

    public function buscarPorID($bonusID = -1, $usuarioID = -1, $carregarDependencias = false) {
        try {

            $row = $this->conexao->query("SELECT * FROM clienteBonus bonusID = $bonusID AND usuarioID = $usuarioID ")->fetch(PDO::FETCH_SERIALIZE);

            if (isset ($row['clienteBonusID']) && $row['clienteBonusID'] > 0) {
                $clienteBonus = new ClienteBonusBean(null, null, $row['valor'], $row['inicio'], $row['fim']);

                if($carregarDependencias){
                    $clienteBonus->setBonus($this->bonusDAO->buscarPorID($row['bonusID']));
                    $clienteBonus->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }

                return $clienteBonus;
            } else {
                return null;
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ClienteBonusDAO:" . $err->getMessage());
        }
    }

    private function getWhere($bonusID = -1, $usuarioID = -1, $inicio = "") {

        $where = " WHERE 1 = 1 ";

        if (isset($bonusID) && $bonusID > 0) {
            $where = $where . " AND u.bonusID = $bonusID ";
        }

        if (isset($usuarioID) && $usuarioID > 0) {
            $where = $where . " AND u.usuarioID = $usuarioID ";
        }

        if (isset($inicio) && strlen($inicio) > 0) {
            $where = $where . " AND u.inicio = '$inicio' ";
        }

        return $where;
    }

    public function total($bonusID = -1, $usuarioID = -1, $inicio = "") {
        try {

            $where = $this->getWhere($bonusID, $usuarioID, $inicio);
            $total = $this->conexao->query("SELECT COUNT(u.clienteBonusID) total FROM clienteBonus u $where")->fetch(PDO::FETCH_COLUMN);
            return $total;
        } catch (PDOException $err) {
            throw new Exception("Erro ClienteBonusDAO:" . $err->getMessage());
        }
    }

}
?>